
package com.jojoteamwork.photo.util;

import com.jojoteamwork.photo.R;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class Utils {

    public static final int IO_BUFFER_SIZE = 8 * 1024;

    public static final String PHOTOPATH = Environment.getExternalStorageDirectory().getPath()
            + "/pictures/";

    public static final String MAGAZINE_DIR = Environment.getExternalStorageDirectory().getPath()
            + "/ota_photo";

    /**
     * Workaround for bug pre-Froyo, see here for more info:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (hasHttpConnectionBug()) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    /**
     * Get the size in bytes of a bitmap.
     * 
     * @param bitmap
     * @return size in bytes
     */
    @SuppressLint("NewApi")
    public static int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        }
        // Pre HC-MR1
        return bitmap.getRowBytes() * bitmap.getHeight();
    }

    /**
     * Check if external storage is built-in or removable.
     * 
     * @return True if external storage is removable (like an SD card), false
     *         otherwise.
     */
    @SuppressLint("NewApi")
    public static boolean isExternalStorageRemovable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    /**
     * Get the external app cache directory.
     * 
     * @param context The context to use
     * @return The external cache dir
     */
    public static File getExternalCacheDir(Context context) {
        if (hasExternalCacheDir()) {
            return context.getExternalCacheDir();
        }

        // Before Froyo we need to construct the external cache dir ourselves
        final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
    }

    /**
     * Check how much usable space is available at a given path.
     * 
     * @param path The path to check
     * @return The space available in bytes
     */
    @SuppressLint("NewApi")
    public static long getUsableSpace(File path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return path.getUsableSpace();
        }
        final StatFs stats = new StatFs(path.getPath());
        return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
    }

    /**
     * Get the memory class of this device (approx. per-app memory limit)
     * 
     * @param context
     * @return
     */
    public static int getMemoryClass(Context context) {
        return ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .getMemoryClass();
    }

    /**
     * Check if OS version has a http URLConnection bug. See here for more
     * information:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     * 
     * @return
     */
    public static boolean hasHttpConnectionBug() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO;
    }

    /**
     * Check if OS version has built-in external cache dir method.
     * 
     * @return
     */
    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    /**
     * Check if ActionBar is available.
     * 
     * @return
     */
    public static boolean hasActionBar() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
    }

    public static void copyFile(String path, InputStream in, boolean overlay) {
        File file = new File(path);
        copyFile(file, in, overlay);
    }

    public static void copyFile(String path, byte[] data, boolean overlay) {
        File file = new File(path);
        copyFile(file, data, overlay);
    }

    private static void copyFile(File file, byte[] data, boolean overlay) {

        BufferedOutputStream out = null;
        if (!checkFile(file, overlay)) {
            return;
        }
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            out.write(data);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static boolean checkFile(File file, boolean overlay) {
        if (file.exists()) {
            if (!overlay) {
                return false;
            } else {
                file.delete();
            }
        } else {
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            // if (!file.exists()) {
            // file.createNewFile();
            // }
        }
        return true;
    }

    public static void copyFile(File file, InputStream in, boolean overlay) {
        if (!checkFile(file, overlay)) {
            return;
        }
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buffer = new byte[1024];
            int count;
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }
            out.flush();
            // out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static boolean getNetState(ConnectivityManager manager) {
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo == null)
            return false;
        return networkInfo.isConnected();
    }

    // public static void savePhotoToSD(DBHelper dbHelper, Model model) {
    // Cursor c = dbHelper.getPhotoCursor(model.id);
    // File file;
    // String path;
    // byte[] data;
    // Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    // while (c.moveToNext()) {
    // data = c.getBlob(0);
    // path = PHOTOPATH + model.name + "/" + (c.getPosition() + 1) + ".jpg";
    // file = new File(path);
    // copyFile(file, data, false);
    // intent.setData(Uri.parse("file://" + path));
    // dbHelper.mContext.sendBroadcast(intent);
    // }
    //
    // c.close();
    // }

    public static boolean checkFile(String filepath) {
        File file = new File(filepath);
        return file.exists();
    }

    /**
     * 显示默认的弹出对话框，该窗口有确定及取消两个按钮，默认点击取消按钮不发生任何事，只把对话框关闭
     * 
     * @param context 上下文
     * @param title 对话框标题
     * @param message 对话框信息
     * @param onClickListener 点击确定时的事件
     */
    public static void showDefaultAlertDialog(Context context, String title, String message,
            OnClickListener onClickListener) {
        new AlertDialog.Builder(context).setTitle(title).setMessage(message)
                .setPositiveButton(R.string.confirm, onClickListener)
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 通过后缀名筛选目录中的文件
     * 
     * @param directory 文件目录
     * @param suffix 后缀名(不带.号)
     * @return 筛选出的文件名
     */
    public static String[] findFilesBySuffix(String directory, final String suffix) {
        File dir = new File(directory);
        if (dir.isDirectory()) {
            String[] list = dir.list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {

                    return filename.contains("." + suffix);
                }
            });
            Arrays.sort(list);
            return list;
        }

        return null;
    }

    public static void deleteFile(String path){
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
    }
    
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

}
